#include <stdio.h>

#include <lua.h>
#include <lauxlib.h>

void print_ref_value(lua_State* L, int ref)
{
	lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
	lua_getfield(L, -1, "name");
	const char* szName = lua_tostring(L, -1);
	printf("test[name]=%s\n", szName);
	lua_pop(L, 2);
}

void test_luaL_ref(lua_State* L)
{
	// { "name" = "test" };
	lua_newtable(L);
	lua_pushstring(L, "test");
	lua_setfield(L, -2, "name");

	// create ref
	lua_pushvalue(L, -1);
	int ref = luaL_ref(L, LUA_REGISTRYINDEX);

	// get value by ref and print it
	print_ref_value(L, ref);

	// change table var
	lua_pushstring(L, "newvalue");
	lua_setfield(L, -2, "name");

	// print new value
	print_ref_value(L, ref);
	
	// unref
	luaL_unref(L, LUA_REGISTRYINDEX, ref);
}

int main()
{
	lua_State* L = luaL_newstate();
	if (L == NULL)
	{
		printf("new state fail!\n");
		return 1;
	}

	// 测试luaL_ref函数
	test_luaL_ref(L);

	lua_close(L);
	return 0;
}
